﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using CYTS.Aoyou.Framework.Utility;

namespace CYTS.Aoyou.Framework.Config
{
    /// <summary>
    /// 配置单元, 所有配置类都要继承此类
    /// </summary>
    public abstract class ConfigUnit
    {
        /// <summary>
        /// 配置最后一次加载的时间；
        /// </summary>
        [XmlIgnore]
        public DateTime LastLoadTime { get; set; }

        /// <summary>
        /// 需要每个子类确定各自对应配置文件位置及名称
        /// </summary>
        [XmlIgnore]
        public virtual string FilePath
        {
            get
            {
                return this.GetType().Name.ToLower().Replace("config", "") + ".config";
            }
        }

        /// <summary>
        /// 配置文件的全路径；
        /// </summary>
        [XmlIgnore]
        public string ConfigFileFullPath
        {
            get
            {
                if (!FileMonitorHelper.MonitorFileFullPathDic.ContainsKey(FilePath.ToLower()))
                {
                    string msg = string.Format("'{0}'下（包括子文件夹）不存在'{1}'", FileMonitorHelper.Path, FilePath);
                    throw new Exception(msg);
                }
                else
                {
                    return FileMonitorHelper.MonitorFileFullPathDic[FilePath.ToLower()];
                }
            }
        }


        /// <summary>
        /// 1.加载配置（反序列化本地文件）
        /// 2.在监控到文件有变化时，也会被调用。
        /// </summary>
        /// <returns></returns>
        internal virtual ConfigUnit OnUpdate()
        {
            lock (this)
            {
                try
                {
                    string filePath = this.ConfigFileFullPath;//System.IO.Path.Combine(Convert.ToString(status), FilePath);
                    ConfigUnit conf = SerializationHelper.Load(this.GetType(), filePath) as ConfigUnit;
                    //更新最后一次加载时间为当前时间
                    conf.LastLoadTime = DateTime.Now;
                    return conf;
                }
                catch (Exception ex)
                {
                    string msg = this.GetType().ToString() + "文件序列化错误";
                    throw new Exception(msg, ex);
                }
            }
        }
    }
}
